package com.hzit.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hzit.entity.LoginUser;
import com.hzit.entity.User;
import com.hzit.mapper.UserMapper;
import com.hzit.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 用户认证逻辑
 */
@Service
public class HzitUserDetailService implements UserDetailsService {
	@Autowired
	private UserMapper userMapper;
	//1. 定义自己的认证（登录验证）实现
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		//1.1 根据用户名查询用户对象
		User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
		if(user == null){
			throw new UsernameNotFoundException("用户名或密码输入有误！");
		}
		//1.2 查询出用户权限串
		List<String> permissions = userMapper.findPermissionsByUsername(username);
		//1.3 返回登录用户
		return new LoginUser(user,permissions);
	}
}
